package Java并发编程;

import java.util.concurrent.locks.LockSupport;

import static java.lang.Thread.sleep;

/**
 * -- 打断sleep,wait,join(阻塞),打断后出现InterruptException异常
 *     打断sleep的线程,会清空打断标记
 *     打断正常运行的线程,不会清空打断标记
 *
 * -- 两阶段终止模式
 *     在一个线程T1中如何优雅的终止T2线程?
 *     错误思路:1.stop()方法   2.exit()方法
 *
 *     interrupted会清空打断标记,isInterrupted不会
 * @author gaofeng
 * date 2022年02月07日 19:48
 */
public class TestTwoPhaseTermination {
    public static void main(String[] args) throws InterruptedException{
       /* TwoPhaseTermination tpt = new TwoPhaseTermination();
        tpt.start();

            sleep(3500);
            tpt.stop();*/
        test();

        // 不推荐的方法,容易破坏同步代码块,造成线程思索
        //stop()--停止  suspend()--挂起  resume()--恢复线程运行
    }

    public static void test() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            System.out.println("park");
            LockSupport.park();
            System.out.println("unpark");
            System.out.println("打断标记: " + Thread.currentThread().isInterrupted());
            //Thread.interrupted() ;


            System.out.println("================");
            // 打印标记为true,会失效
            LockSupport.park();
            System.out.println("unpark");
        }) ;

        t1.start();
        sleep(1) ;
        t1.interrupt();
    }
}

class TwoPhaseTermination {
    private Thread thread ;

    public void start() {
        thread = new Thread(() -> {
            Thread c = Thread.currentThread();
            while (true) {
                if (c.isInterrupted()) {
                    System.out.println("被打断了,");
                    System.out.println("开始料理后事");
                    break;
                }
                try {
                    sleep(1000);
                    System.out.println("没有异常,执行监控记录");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    c.interrupt();
                    System.out.println("设置打断标记");
                }
            }
        });

        thread.start();
    }

    public void stop() {
        thread.interrupt();
    }
}
